package server.handler;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.json.JSONObject;
import server.database.CommentDatabase;
import server.entity.Comment;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CommentHandler implements HttpHandler {
    private CommentDatabase db;
    public CommentHandler() {
        db = CommentDatabase.getInstance();
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {

        Headers headers = exchange.getRequestHeaders();

        String contentType = headers.get("Content-Type").get(0);
        if(contentType.equalsIgnoreCase("application/json")){
            if (exchange.getRequestMethod().equalsIgnoreCase("POST")) {
//                if(!Handler.authentication(exchange)){
//                    Handler.errorHandler(exchange, "Please login or register first");
//                    return;
//                }
                String inputData;
                try{
                    inputData = Handler.getRequestData(exchange);
                }catch (IOException e){
                    Handler.errorHandler(exchange, e);
                    return;
                }

                JSONObject jsonObject = new JSONObject(inputData);
                if(!jsonObject.has("comment")){
                    Handler.errorHandler(exchange, "comment is require");
                }
                if(!jsonObject.has("id")){
                    Handler.errorHandler(exchange, "id is require");
                }

                String id = jsonObject.getString("id");
                String time = jsonObject.getString("sent");
                LocalDateTime date = Handler.localDateTimeToEpochMilli(time);

                Comment comment = new Comment(jsonObject.getString("comment"), date);
                try{
                    db.storecomments(comment, id);
                }catch (Exception e){
                    Handler.errorHandler(exchange, e);
                    return;
                }
                Handler.sendResponse(exchange, "success");

            }else{

                //Code for handling other requests
                Handler.errorHandler(exchange, "Unsupported request method");
            }
        }

    }
}
